import io
import base64
import uuid

from django.core.cache import cache
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView

from baykeadmin.config import default
from baykeadmin.common.utils import (
    generate_catcha_image, 
    random_string
)
from .serializers import SendEmailCodeSerializer


class CaptchaGenericAPIView(GenericAPIView):
    """ 验证码 """
    def get(self, request, *args, **kwargs):
        # uid, base64
        image, text = generate_catcha_image()
        uid = uuid.uuid4().hex
        cache.set(uid, text, 60 * 5)
        image_byte = io.BytesIO()
        image.save(image_byte, format='png')
        image_base64 = base64.b64encode(image_byte.getvalue()).decode()
        return Response({
            'uid': uid,
            'image': image_base64,
            'msg': 'success',
            'code': 200
        })


class SendEmailCodeGenericAPIView(GenericAPIView):
    """发送邮箱验证码"""

    serializer_class = SendEmailCodeSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        #需要执行发送验证码的逻辑
        ## 1. 缓存邮箱和验证码到缓存当中去
        code = random_string(default.EMAIL_CAPTCHA_LENGTH)
        email = serializer.validated_data['email']
        cache.get_or_set(email, code, default.EMAIL_CAPTCHA_EXPIRED_TIME)
        ## 2. 发送验证码到邮箱
        from django.core.mail import send_mail
        send_mail(
            subject='您的邮箱验证码已发送，请查收！',
            message=f'您的验证码是:{code}',
            from_email='admin@qq.com',
            recipient_list=[email],
            fail_silently=False,
        )
        return Response({'msg': '发送成功', 'code': 200})